package com.msb.mall.carts.service.impl;

import com.alibaba.fastjson.JSON;
import com.msb.common.constant.CartConstant;
import com.msb.common.dto.MemberDTO;
import com.msb.common.utils.R;
import com.msb.mall.carts.config.MyThreadPoolExecutor;
import com.msb.mall.carts.feign.ProductFeignService;
import com.msb.mall.carts.interceptor.AuthInterceptor;
import com.msb.mall.carts.service.CartService;
import com.msb.mall.carts.vo.Cart;
import com.msb.mall.carts.vo.CartItem;
import com.msb.mall.carts.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 购物车详情
     */
    @Override
    public Cart getCartList() {
        MemberDTO memberDTO = AuthInterceptor.threadLocal.get();
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(CartConstant.CART_PERFIX+ memberDTO.getNickname());
        Set<Object> keys = ops.keys();
        Cart cart = new Cart();
        ArrayList<CartItem> list = new ArrayList<>();
        for (Object key : keys) {
            Object o = ops.get((String) key);
            CartItem cartItem = JSON.parseObject((String) o, CartItem.class);
            list.add(cartItem);
        }
        cart.setItems(list);
        return cart;
    }

    /**
     * 加入购物车
     * @param skuId
     * @param count 购买的商品数量
     */
    @Override
    public CartItem addCart(Long skuId, Integer count) throws ExecutionException, InterruptedException {
        // 获取用户
        MemberDTO dto = AuthInterceptor.threadLocal.get();
        BoundHashOperations ops = redisTemplate.boundHashOps(CartConstant.CART_PERFIX + dto.getNickname());
        Object o = ops.get(skuId.toString());
        if (null != o){
            // 该商品已加入购物车，更新数量
            CartItem cartItem = JSON.parseObject((String) o, CartItem.class);
            cartItem.setCount(cartItem.getCount()+count);
            ops.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
        // redis不存在该商品,添加
        // 调用product服务获取商品信息
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            R r = productFeignService.info(skuId);
            SkuInfoVo skuInfo = JSON.parseObject(JSON.toJSONString(r.get("skuInfo")), SkuInfoVo.class);
            cartItem.setSkuId(skuId);
            cartItem.setCount(count);
            cartItem.setImage(skuInfo.getSkuDefaultImg());
            cartItem.setPrice(skuInfo.getPrice());
            cartItem.setTitle(skuInfo.getSkuTitle());
        }, executor);

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            // 销售属性
            List<String> skuAttr = new ArrayList<>();
            R saleR = productFeignService.getSaleAttrBySkuId(skuId);
            String saleAttr = JSON.toJSONString(saleR.get("saleAttr"));
            List list = JSON.parseObject(saleAttr, List.class);
            cartItem.setSkuAttr(list);
        }, executor);

        CompletableFuture.allOf(future1,future2).get();
        // 购物车信息存储到redis
        ops.put(skuId.toString(),JSON.toJSONString(cartItem));
        return cartItem;
    }
}
